package controller;


import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import pojo.Books;
import pojo.Goods;
import pojo.Healths;
import service.GoodService;
import service.GoodServiceImpl;
import service.HealthService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

@Controller
public class GoodController {

    @Autowired
    @Qualifier("GoodServiceImpl")
    private GoodServiceImpl goodService;


    @ResponseBody
    @RequestMapping(value = "/allGoods", produces = "text/html;charset=utf-8")
    public String allHealth(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/json; charset=utf-8");    // 设置response的编码及格式

        List<Goods> list = goodService.queryAllBook();
        String resJSON = JSON.toJSONString(list);     // 转换为json
        return resJSON;
    }


    @CrossOrigin(origins = "*")
    @RequestMapping(value = "/addGood", produces = "text/html;charset=utf-8")
    public void addGoods(Goods goods, HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization,token, content-type");
        System.out.println("增加" + goods);
        goodService.addBook(goods);
    }

    @CrossOrigin(origins = "*")
    @RequestMapping("/delGood/{id}")
    public void deleteBook(@PathVariable("id") int id, HttpServletResponse response, HttpServletRequest request){
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization,token, content-type");
        System.out.println(id);
        goodService.deleteBookById(id);
    }
}


